package com.vn.ld.order.domain.queue.manager;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.activation.UnsupportedDataTypeException;
import javax.naming.TimeLimitExceededException;

import org.apache.log4j.Logger;

import com.vn.ld.btc.dao.entity.Order;
import com.vn.ld.order.service.management.OrderManager;

public class CustomerOrderQueueManager implements Runnable{
	
	private Logger logger = Logger.getLogger(this.getClass());
	private BlockingQueue<Order> custOrderQueue;
	OrderManager orderManager = null;
	
	private static CustomerOrderQueueManager custOrderManager = null;
	
	private CustomerOrderQueueManager(BlockingQueue<Order> custOrderQueue){
		this.custOrderQueue = custOrderQueue;  
		this.orderManager = OrderManager.getInstance();
	}

	public static synchronized CustomerOrderQueueManager getInstance(){
		
		if(custOrderManager == null){
			custOrderManager = new CustomerOrderQueueManager(new LinkedBlockingQueue<Order>());		
			
			Thread custOrderThread = new Thread(custOrderManager, "Customer order queue manager");
			custOrderThread.start();
		}
		
		return custOrderManager;
	}
	
	public BlockingQueue<Order> getCustOrderQueue(){
		return custOrderQueue;
	}
	
	@Override
	public void run() {
		try {
			Order order = custOrderQueue.take();
			orderManager.manageOrder(order);
			
		} catch (InterruptedException | TimeLimitExceededException | UnsupportedDataTypeException e) {
			//TODO handle the error
			logger.fatal(e);
			e.printStackTrace();
		}
		
	}
	
	
	
}
